﻿using System;
using System.Data;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Collections.Generic;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormHealthCheck : FormBaseDataMstDtl
    {
        private DataSet mdsHealthBas, mdsHealthDtl;
        private SqlDataAdapter mdaHealthDtlUpdate;
        private Ctrl_General mCtrlGeneral;
        private CurrencyManager mCurrencyManagerHealthDtl;

        public FormHealthCheck()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                LoadData();
                LoadDataDetails();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot open Health Check'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        #region LoadData
        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                ClearDataBinding(this);
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string ls_SQL = " Select HC.ID_Emp, PP.Emp_NameVN, HC.ID_HealthCheck, HC.Height, HC.Weight, HC.Blood, HC.Health_Status, HC.CreatedUser, HC.UpdatedUser, HC.CreatedDate, HC.UpdatedDate "
                + " From HRM_PersonnelHelthCheckBas HC inner join HRM_PersonalProfile PP on HC.ID_Emp = PP.ID_Emp ";

                mdsHealthBas = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelHelthCheckBas");

                if (mdsHealthBas == null) return;
                //Binding: TextBox, Label
                txtIDEmp.DataBindings.Add(new Binding("Text", mdsHealthBas.Tables[0], "ID_Emp"));
                lblFullName.DataBindings.Add(new Binding("Text", mdsHealthBas.Tables[0], "Emp_NameVN"));
                nudHeight.DataBindings.Add(new Binding("Value", mdsHealthBas.Tables[0], "Height"));
                nudWeight.DataBindings.Add(new Binding("Value", mdsHealthBas.Tables[0], "Weight"));
                txtBloodGrp.DataBindings.Add(new Binding("Text", mdsHealthBas.Tables[0], "Blood"));
                txtHealthStatus.DataBindings.Add(new Binding("Text", mdsHealthBas.Tables[0], "Health_Status"));

                mRowManager = (CurrencyManager)txtIDEmp.BindingContext[mdsHealthBas.Tables[0]];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                SetData2List(mdsHealthBas);
                //SetReadOnly(this, false);
                base.LoadMasterData();
                SetAdd(false);
                SetDelete(false);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load header data'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region LoadDataDetails
        private void LoadDataDetails()
        {
            try
            {
                if (mdsHealthBas == null || mdsHealthBas.Tables[0].Rows.Count <= 0) return;
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string ls_IDHealthCheck = mdsHealthBas.Tables[0].Rows[0]["ID_HealthCheck"].ToString();

                string lCondition = " ID_HealthCheck = " + ls_IDHealthCheck + "";

                mdsHealthDtl = mCtrlGeneral.GetDataWithCondition(out mdaHealthDtlUpdate, "HRM_PersonnelHealthCheckDtl", lCondition);

                if (mdsHealthDtl == null) return;

                mdbg_DetailGrid.DataSource = mdsHealthDtl;
                mdbg_DetailGrid.DataMember = "HRM_PersonnelHealthCheckDtl";
                mdbg_DetailGrid.Columns["ID_HealthCheck"].Visible = false;

                mCurrencyManagerHealthDtl = (CurrencyManager)mdbg_DetailGrid.BindingContext[mdsHealthDtl, "HRM_PersonnelHealthCheckDtl"];
                mCurrencyManagerHealthDtl.PositionChanged += new EventHandler(RowMaster_Changed);
                

                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load health check details'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Move Events
        public override void move_first()
        {
            base.move_first();
            LoadDataDetails();
            if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
        }

        public override void move_last()
        {
            base.move_last();
 
            LoadDataDetails();
            if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            
        }

        public override void move_next()
        {
            base.move_next();
           LoadDataDetails();
           if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
        }

        public override void move_previous()
        {
            base.move_previous();
            LoadDataDetails();
            if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
        }
        #endregion

        #region add
        public override void add()
        {
           
        }
        #endregion

        #region modify
        public override void modify()
        {
            base.modify();
            ModifyDetails();
        }
        #endregion

        #region save
        public override void save()
        {
            if (mdsHealthBas == null || mdsHealthBas.Tables[0].Rows.Count<=0) return;
            
            if (!SaveDetails()) return;
            base.save();
            SetAdd(false);
            SetDelete(false);
        }
        #endregion

        #region cancel
        public override void cancel()
        {
            if (mdsHealthBas == null) return;
            
            base.cancel();
            CancelDetails();
            SetAdd(false);
            SetDelete(false);
        }
        #endregion

        #region Modify details
        private void ModifyDetails()
        {
            mdbg_DetailGrid.Focus();
            mdbg_DetailGrid.AllowUserToAddRows = true;
            mdbg_DetailGrid.AllowUserToOrderColumns = false;
            mCurrencyManagerHealthDtl.Position = mdsHealthDtl.Tables[0].Rows.Count;
        }
        #endregion

        #region Save Details
        private bool SaveDetails()
        {
            try
            {
                if (mdsHealthDtl == null || txtIDEmp.Text.Equals(""))
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }
                mdsHealthDtl = (DataSet)mdbg_DetailGrid.DataSource;
                if (mdsHealthDtl.Tables[0].Rows.Count == 0)
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsHealthDtl.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["ID_HealthCheck"].ToString() != "" && ldr["ID_HealthCheck"].ToString() != mdsHealthBas.Tables[0].Rows[mRowManager.Position]["ID_HealthCheck"].ToString())
                        {
                            mdbg_DetailGrid.AllowUserToAddRows = false;
                            mdbg_DetailGrid.AllowUserToOrderColumns = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_DetailGrid.AllowUserToAddRows = false;
                        mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    }
                }

                mCurrencyManagerHealthDtl.EndCurrentEdit();

                if (!mdsHealthDtl.HasChanges())
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsHealthDtl.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_HealthCheck"] = mdsHealthBas.Tables[0].Rows[mRowManager.Position]["ID_HealthCheck"];
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaHealthDtlUpdate, ldsHasChanged, "HRM_PersonnelHealthCheckDtl", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsHealthDtl.AcceptChanges();
                    LoadDataDetails();
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot update'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion

        #region Cancel Details
        private void CancelDetails()
        {
            if (mdsHealthDtl != null)
            {
                if (mdsHealthDtl.Tables[0].Rows.Count > 0)
                {

                    mCurrencyManagerHealthDtl.EndCurrentEdit();
                    mdsHealthDtl.RejectChanges();
                }
                else
                    mdsHealthDtl.Clear();
            }
            mdbg_DetailGrid.AllowUserToAddRows = false;
        }
        #endregion


        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

    }
}
